<template>
  <page-header-wrapper>
    <!-- 列表页 -->
    <a-card v-show=" !vdata.currentApplyPage.component" class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="resetFunc">
        <!-- 时间搜索控件 -->
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker
            ref="dateRangePicker"
            v-model:value="vdata.searchData['queryDateRange']"
            customDateRangeType="date"
          />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData['unionSearchId']" :placeholder="'系统/渠道申请单号'" />
        <JeepaySearchInfoInput v-model:value="vdata.searchData.mchNo" placeholder="商户号" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />

        <jeepay-text-up v-model:value="vdata.searchData['mchFullName']" :placeholder="'进件商户名'" />

        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.merchantType" placeholder="商户类型">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="1">小微</a-select-option>
            <a-select-option value="2">个体</a-select-option>
            <a-select-option value="3">企业</a-select-option>
          </a-select>
        </a-form-item>

        <JeepaySelect ref="stateRef" placeholder="进件状态" :reset="isReset">
          <a-select v-model:value="vdata.searchData.state" @change="stateRef.textupHandle()">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">草稿</a-select-option>
            <a-select-option value="1">审核中</a-select-option>
            <a-select-option value="2">进件成功</a-select-option>
            <a-select-option value="3">驳回待修改</a-select-option>
            <a-select-option value="4">待验证</a-select-option>
            <a-select-option value="5">待签约</a-select-option>
            <a-select-option value="6">签约完成</a-select-option>
            <a-select-option value="7">等待预审</a-select-option>
            <a-select-option value="8">预审拒绝</a-select-option>
          </a-select>
        </JeepaySelect>

        <JeepaySelect ref="ifCodeRef" placeholder="支付接口" :reset="isReset">
          <a-select v-model:value="vdata.searchData.ifCode" @change="ifCodeRef.textupHandle()">
            <a-select-option value="">全部</a-select-option>
            <template v-for="(item) in vdata.ifCodeList" :key="item.ifCode">
              <a-select-option :value="item.ifCode">{{ item.ifName }}[{{ item.ifCode }}]</a-select-option>
            </template>
          </a-select>
        </JeepaySelect>
      </JeepaySearchForm>


      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="false"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        row-key="applyId"
      >
        <!-- 表格顶部按钮行插槽 -->
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_MCH_APPLYMENT_ADD')" type="primary" @click="addFunc('')"><plus-outlined />发起进件</a-button>
        </template>

        <!-- body 渲染插槽 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'state'">
            <a-badge v-if="record.state == 0" status="default" text="草稿" />
            <a-badge v-if="record.state == 1" status="warning" text="等待审核结果" />
            <a-badge v-if="record.state == 2" status="success" text="进件成功" /> 
            <a-badge v-if="record.state == 3" status="error" text="驳回待修改" /> 
            <a-badge v-if="record.state == 4" status="processing" text="待验证" /> 
            <a-badge v-if="record.state == 5" status="processing" text="待签约" /> 
            <a-badge v-if="record.state == 6" status="processing" text="签约完成" />
            <a-badge v-if="record.state == 7" status="processing" text="等待预审" />
            <a-badge v-if="record.state == 8" status="processing" text="预审拒绝" />

            <a-tooltip v-if="record.applyErrorInfo && record.state != 2" :title="record.applyErrorInfo">
              <info-circle-outlined />
            </a-tooltip>
            <QrcodeOutlined v-if="record.state == 5 && record.ifCode === 'alipay'" style="font-size: 16px;margin-left: 10px;" @click="showQrImgFunc(record)" />
            <QrcodeOutlined
              v-if="(record.state == 4 || record.state == 5) && (record.ifCode === 'wxpay' || record.ifCode === 'sftpay')" 
              style="font-size: 16px;margin-left: 10px;" 
              @click="showQrImgFunc(record)" 
            />
          </template>

          <template v-if="column.key === 'type'">
            <a-tag :color="record.type === 1 ? 'green' : 'orange'">
              {{ record.type === 1 ? '普通商户':'特约商户' }}
            </a-tag>
          </template>

          <template v-if="column.key === 'applyId'">
            <a @click="detailFunc(record.applyId)"><b>{{ record.applyId }}</b></a>
          </template>

          <template v-if="column.key === 'merchantType'">
            {{ record.merchantType === 1 ? '小微':record.merchantType === 2 ? '个体':record.merchantType === 3 ? '企业':'其他组织' }}
          </template>

          <template v-if="column.key === 'applyPageType'">
            <span v-if="record.applyPageType == 'PLATFORM_WEB'">运营平台系统</span>
            <span v-else-if="record.applyPageType == 'AGENT_WEB'">代理商系统</span>
            <span v-else-if="record.applyPageType == 'AGENT_APP'">{{ $SYS_NAME_MAP.AGENT_APP }}APP</span>
            <span v-else-if="record.applyPageType == 'AGENT_LITE'">{{ $SYS_NAME_MAP.AGENT_APP }}小程序</span>
            <span v-else-if="record.applyPageType == 'MCH_WEB'">商户系统</span>
            <span v-else-if="record.applyPageType == 'MCH_APP'">{{ $SYS_NAME_MAP.MCH_APP }}APP</span>
            <span v-else-if="record.applyPageType == 'MCH_LITE'">{{ $SYS_NAME_MAP.MCH_APP }}小程序</span>
            <span v-else>{{ record.applyPageType || '' }}</span>
          </template>

          <template v-if="column.key === 'operation'">
            <!-- 以下为： 运营， 代理商通用按钮 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_MCH_APPLYMENT_VIEW')" type="link" @click="editOrViewFunc(record.applyId, true)">详情</a-button>
              <a-button v-if="$access('ENT_MCH_APPLYMENT_VIEW')" type="link" @click="detailFunc(record.applyId)">详细数据</a-button>
              <a-button v-if="$access('ENT_MCH_APPLYMENT_EDIT') && record.state == 0" type="link" @click="editOrViewFunc(record.applyId, false)">继续填写</a-button>
              <a-button v-if="$access('ENT_MCH_APPLYMENT_EDIT') && record.state == 3" type="link" @click="editOrViewFunc(record.applyId, false)">修改</a-button>
              <a-button v-if="$access('ENT_MCH_APPLYMENT_ADD')" type="link" @click="toCopySelectIfCodePage(record.applyId, record.mchNo)">副本</a-button>

           
              <!-- 审核中、 待验证、 签约完成 -->
              <a-button
                v-if="$access('ENT_MCH_APPLYMENT_GET_INFO') && (record.state == 1 || record.state == 4 || record.state == 5)"
                type="link" 
                @click="queryChannelState(record.applyId, record.state)"
              >
                获取最新结果
              </a-button>

              <!-- 进件成功后可发起 参数配置 -->
              <a-button v-if="$access('ENT_MCH_APPLYMENT_PAY_CONFIG') && record.state == 2" type="link" @click="appConfigDrawerRef.show(record.applyId)">参数配置</a-button>

              <!-- 1审核中、 2进件成功、 4待验证、 5待签约、 6签约完成/审核成功 -->
              <a-button
                v-if="$access('ENT_MCH_APPLYMENT_SIGN') && (record.state == 1 || record.state == 2 || record.state == 4 || record.state == 5 || record.state == 6)"
                type="link" 
                @click="nextBizsDrawerRef.show(record.applyId)"
              >
                签约开通
              </a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>

      <a-modal v-model:visible="vdata.qrCodeVisible" title="商户签约二维码" :footer="null" :width="250" @ok="() => vdata.qrCodeVisible = false">
        <QrcodeVue :value="vdata.confirmUrl" :size="200" />
      </a-modal>
      <!-- 微信签约弹窗 -->
      <a-modal v-model:visible="vdata.wxQrCodeVisible" title="二维码" :footer="null" :width="250" @ok="() => vdata.wxQrCodeVisible = false">
        <span>请超级管理员使用微信扫描二维码，根据页面指引完成签约</span>
        <img :src="vdata.confirmUrl" style="width: 200px;height: 200px;">
      </a-modal>
      <!-- 收付通签约弹窗 -->
      <a-modal v-model:visible="vdata.sftQrCodeVisible" title="二维码" :footer="null" :width="250" @ok="() => vdata.sftQrCodeVisible = false">
        <span>请超级管理员使用微信扫描二维码，根据页面指引完成签约</span>
        <QrcodeVue :value="vdata.confirmUrl" style="padding-top: 10px;" :size="200" />
      </a-modal>
    </a-card>

    <!-- 定义组件分为： 第一步和第二步  -->
    <a-card>
      <component :is="vdata.currentApplyPage.component" ref="applyPageComponentRef" :listPageSearchMchNo="vdata.searchData.mchNo" @switchApplyPage="switchApplyPage" />
    </a-card>

    <JeepayModelMchList ref="jeepayModelMchList" showType="MCH" @selectFinishFunc="searchMchFinishFunc" />

    <!-- 参数配置 弹层 -->
    <AppConfigDrawer ref="appConfigDrawerRef" />

    <!-- 后续流程 弹层 -->
    <NextBizsDrawer ref="nextBizsDrawerRef" />

    <!-- 详情页面组件  -->
    <InfoDetail ref="infoDetail" :callback-func="searchFunc" />
  </page-header-wrapper>
</template>
<script setup lang="ts">
import { API_URL_MCH_APPLYMENT_LIST, req, $getMchApplymentChannelState, $getPayConfigIfcodes } from '@/api/manage'
import {ref, reactive, getCurrentInstance, nextTick, provide, computed, onMounted } from 'vue'
import QrcodeVue from 'qrcode.vue'
import ApplySelectMchAndIfcode from '@/components/link/JeepayUIComponents/JeepayMchApplyment/JeepayMchApplymentSelectMchAndIfcode.vue'
import ApplyMchDetailInfoEntry from '@/components/link/JeepayUIComponents/JeepayMchApplyment/JeepayMchApplymentDetailInfoEntry.vue'
import AppConfigDrawer from './AppConfigDrawer.vue'
import NextBizsDrawer from './NextBizsDrawer.vue'
import InfoDetail from './Detail.vue'
import { useRoute } from 'vue-router'
const { $infoBox, $access, $SYS_NAME_MAP } = getCurrentInstance()!.appContext.config.globalProperties


/** 定义全部组件 **/
const allApplyPage = {
  'list': { name: '列表', component: null },
  'applySelectMchAndIfcode': { name: '选择商户及进件渠道', component: ApplySelectMchAndIfcode },
  'applyMchDetailInfoEntry':  { name: '填写进件资料', component: ApplyMchDetailInfoEntry }
}

// 动态组件
const applyPageComponentRef = ref()

const jeepayModelMchList = ref()

const appConfigDrawerRef = ref()
const nextBizsDrawerRef = ref()
const infoDetail = ref()
const infoTable = ref()
const dateRangePicker = ref()

let tableColumns = reactive([
  { key: 'applyId', title: '申请单号', dataIndex: 'applyId', },
  { key: 'ifName', title: '渠道', dataIndex: 'ifName' , },
  { key: 'merchantType', title: '商户类型', dataIndex: 'merchantType' , },
  { key: 'mchNo', title: '商户号', dataIndex: 'mchNo' ,  },
  { key: 'mchFullName', title: '进件商户名', dataIndex: 'mchFullName', },
  // { key: 'isvNo', title: '服务商号', dataIndex: 'isvNo',  width: 140, minWidth: 140, maxWidth: 170},
  { key: 'state', title: '进件状态', },
  // { key: 'applyPageType', title: '来源', width: 150, minWidth: 150, maxWidth: 150},
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期', },
  { key: 'lastApplyAt', dataIndex: 'lastApplyAt', title: '最后提交', },
  { key: 'operation', title: '操作',   fixed: 'right', align: 'center'}
])

  let vdata : any = reactive({

      searchData: { queryDateRange: '' }, // 搜索条件

      currentApplyPage: allApplyPage.list, // 当前的步骤组件  null表示列表页
      backupApplyPage: null, // 备份： 用作快速恢复

      mchApplymentData: { }, //商户进件资料
      isView: false, // 是否预览模式

      ifCodeList: [],

      copyInfoSourceApplyId: '',  // 副本资料

  })

  
onMounted(() => {
  vdata.searchData['mchNo'] = useRoute().query.mchNo
   if($access('ENT_MCH_APPLYMENT')){
      $getPayConfigIfcodes('CURRENT', 'agentApplyment', '').then((res) => {
        vdata.ifCodeList = res
      })
   }
  searchFunc()
})


// 向所有子组件注入参数 (子组件可直接更改此值)
provide('mchApplymentData', computed( ()=> vdata.mchApplymentData) )
provide('isView', computed( ()=> vdata.isView) )

// 向所有子组件注入参数： 配置模式： mgrApplyment / agentApplyment / mchApplyment
provide('configMode', 'agentApplyment')

// 向所有子组件注入参数 副本资料来源ID
provide('copyInfoSourceApplyId', computed( ()=> vdata.copyInfoSourceApplyId) )

    // 请求table接口数据
  function reqTableDataFunc(params: any) {
      return req.list(API_URL_MCH_APPLYMENT_LIST, params)
  }

   // 点击【查询】按钮点击事件
  function searchFunc () {
      infoTable.value.refTable(true)
  }

// 切换步骤： 不清空数据
function switchApplyPage(page){
  vdata.backupApplyPage = vdata.currentApplyPage
  vdata.currentApplyPage = allApplyPage[page]

  if(vdata.currentApplyPage && vdata.currentApplyPage.component){
    nextTick(() => { applyPageComponentRef.value.pageRender() })
  }else{

      //列表页
      searchFunc() // 刷新

  }
}

function detailFunc (recordId: any) { // 进件详情页

  vdata.copyInfoSourceApplyId = '' // 副本清空。 

  infoDetail.value.show(recordId)
}

// 点击【发起进件】的操作
function addFunc(copyInfoSourceApplyId = ''){

  vdata.copyInfoSourceApplyId = copyInfoSourceApplyId

  vdata.backupApplyPage = null // 再次点击进件将无法再次恢复

  //进件数据重置
  vdata.mchApplymentData = {}
  vdata.isView = false
  switchApplyPage('applySelectMchAndIfcode')
}

  // 修改资料 然后重新发起进件操作 
function editOrViewFunc(applyId, isView){

  vdata.copyInfoSourceApplyId = '' // 副本清空。 

  vdata.backupApplyPage = null // 再次点击进件将无法再次恢复
  vdata.isView = isView

  req.getById(API_URL_MCH_APPLYMENT_LIST, applyId, { originData: vdata.isView?'0':'1' } ).then(res => {
    let { applyId, channelApplyNo, mchNo, ifCode, applyDetailInfo, applyErrorInfo, state } = res
    vdata.mchApplymentData = {applyId, channelApplyNo, mchNo, ifCode, applyDetailInfo, applyErrorInfo, state}
    switchApplyPage('applyMchDetailInfoEntry')
  })

}

// 查询最新状态
function queryChannelState(applyId, currState){
  $getMchApplymentChannelState(applyId).then(res => {
      if(currState != res.state){
        $infoBox.message.success('状态已更新')
        searchFunc() // 更新列表
      }else{
        $infoBox.message.info('状态无变化')
      }
  })
}


// 恢复上一次步骤
function recoveryApplyPage(){
  vdata.currentApplyPage = vdata.backupApplyPage
}

// 获取下拉框组件
const ifCodeRef = ref()
const stateRef = ref()
let isReset = ref(0) // 下拉搜索框是否重置

// 清空搜索项
const resetFunc = () => { 
  isReset.value++ // 下拉搜索框重置
  dateRangePicker.value.returnSelectModel()
  vdata.searchData= {}
}

// 选择商户 / 应用 完成后的操作
function searchMchFinishFunc(selectVal){

  if(selectVal[0]){
    vdata.searchData.mchNo = selectVal[0]
  }

  jeepayModelMchList.value.close()

}

// 显示二维码图片
function showQrImgFunc(record){
  if (record.ifCode == 'wxpay') {
    vdata.wxQrCodeVisible = true
  }else if (record.ifCode == 'sftpay') {
    vdata.sftQrCodeVisible = true
  }else if (record.ifCode == 'fuioupay') {
    vdata.qrCodeVisible = true
    vdata.confirmUrl = JSON.parse(record.applyErrorInfo).signUrl
    return
  }else {
    vdata.qrCodeVisible = true
  }
  vdata.confirmUrl = record.applyErrorInfo
}


// 副本 copySourceApplyId : 需要copy的资料来源。 
function toCopySelectIfCodePage(copySourceApplyId, mchNo){

  vdata.searchData.mchNo = mchNo
  addFunc(copySourceApplyId)

}


</script>
